<template>
  <page-container
    showBack
    showTitle>
    <template v-slot:left-title>
      <span class="movieName">{{ `《${$route.query.name}》` }}</span
      >影片的明细数据
    </template>
    <search-form
      v-model="searchForm"
      :searchColumns="searchColumns"
      :searchOptions="{ menuSpan: 15 }"
      @on-search="handleSearch">
      <template v-slot:newBtn>
        <el-button
          type="primary"
          @click="allForm('add')"
          >新增集</el-button
        >
        <el-button
          v-if="showEdit"
          type="primary"
          @click="editCoins('coins')"
          >批量修改单价</el-button
        >
        <el-button
          v-if="showEdit"
          type="primary"
          @click="editCoins('date')"
          >批量修改日期</el-button
        >
      </template>
    </search-form>

    <avue-table
      :dataList="dataList"
      :loading="loading"
      :page="page"
      :tableColumns="tableColumns"
      :tableOptions="{ menuWidth: 180, selection: true }"
      @onPageChange="onPageChange"
      @handleSelectionChange="handleSelectionChange">
      <template v-slot:menu="{ row }">
        <el-button
          type="primary"
          @click="handleVideo(row)"
          icon="el-icon-video-play"
          circle></el-button>
        <el-button
          type="primary"
          @click="allForm('edit', row)"
          icon="el-icon-edit"
          circle></el-button>
        <el-button
          type="primary"
          @click="downLoadMp4(row)"
          icon="el-icon-download"
          circle></el-button>
        <el-button
          @click="delRow(row.id)"
          type="danger"
          icon="el-icon-delete"
          circle></el-button>
      </template>
    </avue-table>

    <el-dialog
      :title="`《${$route.query.name}》`"
      :visible.sync="dialogVisible"
      width="80%"
      height="50%">
      <div id="mse"></div>
    </el-dialog>
  </page-container>
</template>

<script>
import tableMixins from '@/mixins/table'
import { deepClone } from '@/utils'
import { mapGetters } from 'vuex'
import { searchColumns, tableColumns } from './config/table-config'
import { allDialogForm } from './config/dialogForm'
import {
  handleMovieChil,
  addMovieChil,
  editMovieChil,
  delMovieChil,
  editMoviesCoins,
} from '@/api/movie'
import Player from 'xgplayer'
import HlsPlayer from 'xgplayer-hls'
import 'xgplayer/dist/index.min.css'

export default {
  mixins: [tableMixins],
  data() {
    return {
      isMute: true,
      showEdit: false,
      dialogVisible: false,
      dataList: [],
      childList: [],
      movieList: [],
      selectionList: [],

      searchForm: {
        dateRange: [],
      },
      editForm: {},
      diaForm: {
        url: [],
      },
    }
  },
  watch: {
    selectionList(newVal) {
      if (newVal.length === 0) {
        this.showEdit = false
      } else {
        this.showEdit = true
      }
    },
  },
  computed: {
    ...mapGetters(['commonData']),
    userList() {
      return this.commonData?.userList ?? []
    },
    bonusOption() {
      const t = [
        { value: 600, label: '用户购买后,10分钟' },
        { value: 1, label: '用户购买后,1天' },
        { value: 7, label: '用户购买后,7天' },
        { value: 15, label: '用户购买后,15天' },
        { value: 30, label: '用户购买后,30天' },
        { value: 45, label: '用户购买后,45天' },
        { value: 60, label: '用户购买后,60天' },
        { value: 90, label: '用户购买后,90天' },
        { value: 180, label: '用户购买后,180天' },
        { value: 360, label: '用户购买后,360天' },
      ]
      const r_t = t.map(item => {
        return {
          ...item,
          value: item?.value === 600 ? item?.value : item?.value * 86400,
        }
      })
      return r_t
    },
    allDialogForm,
    searchColumns,
    tableColumns,
  },
  methods: {
    fetchMethod: handleMovieChil,
    delMethod: delMovieChil,

    // 查询参数格式化
    formatSearch() {
      const searchParams = deepClone(this.searchForm)
      searchParams.film_id = this.$route.query.id
      return searchParams
    },
    // downLoadMp4(row) {
    //   const url = row.url[0].replace('.m3u8', '.mp4')
    //   const video = `${this.$route.query.cdn}/${url}`
    //   console.log('video:', video)
    //   console.log('row:', row)
    //   const link = document.createElement('a')
    //   link.style.display = 'none'
    //   link.download = `${row.film_name}_${row.episode_no}`
    //   link.href = video
    //   document.body.appendChild(link)
    //   link.click()
    //   console.log('link:', link)
    //   document.body.removeChild(link)
    // },

    // downLoadMp4(row) {
    //   const url = row.url[0].replace('.m3u8', '.mp4')
    //   const video = `${this.$route.query.cdn}/${url}`
    //   console.log('video:', video)
    //   console.log('row:', row)
    //   fetch(video)
    //     .then(response => response.blob())
    //     .then(blob => {
    //       const link = document.createElement('a')
    //       link.style.display = 'none'
    //       link.download = `${row.film_name}_${row.episode_no}`
    //       link.href = video
    //       document.body.appendChild(link)
    //       link.click()
    //       console.log('link:', link)
    //       document.body.removeChild(link)
    //     })
    //     .catch(error => console.error('Error downloading file:', error))
    // },

    downLoadMp4(row) {
      const url = row.url[0].replace('.m3u8', '.mp4')
      const video = `${this.$route.query.cdn}/${url}`
      const newWindow = window.open(video, '_blank')
      newWindow.document.title = `${row.film_name}_${row.episode_no}.mp4`
    },

    // downLoadMp4(row) {
    //   const url = row.url[0].replace('.m3u8', '.mp4')
    //   const filePath = `${this.$route.query.cdn}/${url}`
    //   const fileName = `${row.film_name}_${row.episode_no}.mp4`
    //   const a = document.createElement('a')
    //   document.body.append(a)
    //   a.style.display = 'none'
    //
    //   // 指示回复的内容该以何种形式展示(是以内联的形式（即网页或者页面的一部分），还是以附件的形式下载并保存到本地。)
    //   a.href = filePath
    //   a.download = fileName
    //   a.click()
    //
    //   // 多文件时remove放在setTimeout里面
    //   setTimeout(() => {
    //     document.body.removeChild(a)
    //   }, 300)
    // },
    handleVideo(row) {
      const url = row?.url.find(item => item?.indexOf('m3u8') != -1)
      this.dialogVisible = true
      this.$nextTick(() => {
        const mse = document.querySelector('#mse')
        let config = {
          el: mse,
          height: '500px',
          width: '100%',
          plugins: [HlsPlayer],
          defaultPlaybackRate: 2,
          playbackRate: [0.5, 0.75, 1, 1.5, 2, 5, 8, 10], //倍速
          url: `${this.$route.query.cdn}/${url}`,
        }
        const player = new Player(config)
      })
    },

    allForm(type, row) {
      let formData = {}
      formData = deepClone(this.diaForm)
      if (type === 'edit') {
        formData = deepClone(row)
        formData.coins = row?.coins / 10000
        formData.film_id = this.$route.query.name
        formData.url = formData.url?.map(item => ({ value: item }))
      }
      this.$dialogForm.show({
        title: `${type === 'add' ? '新增' : '编辑'}集`,
        width: '50%',
        data: formData,
        option: {
          span: 24,
          labelWidth: 120,
          column: this.allDialogForm,
        },
        callback: async ({ data, close }) => {
          let resData = {}
          data.coins = data?.coins * 10000
          if (type === 'add') {
            const url = data?.url.map(it => it.value)
            data.url = JSON.stringify(url)
            data.film_id = this.$route.query.id
            delete data?.film_name
            resData = await addMovieChil(data)
          } else {
            const url = data?.url.map(it => it.value)
            data.film_id = this.$route.query.id
            data.url = JSON.stringify(url)
            delete data?.film_name
            resData = await editMovieChil(data)
          }
          if (resData.code === 0) {
            this.$message.success(`${type === 'add' ? '新增' : '编辑'}成功`)
          }
          close()
          this.getList()
        },
      })
    },
    handleSelectionChange(selection) {
      this.selectionList = selection
    },
    editCoins(type) {
      this.$dialogForm.show({
        title: `批量修改${type === 'coins' ? '单价' : '过期时间'}`,
        width: '30%',
        option: {
          span: 24,
          column: [
            {
              display: type === 'coins',
              type: 'number',
              label: '集单价',
              prop: 'coins',
            },
            {
              filterable: true,
              display: type === 'date',
              type: 'select',
              label: '过期日期',
              prop: 'valid_duration',
              dicData: this.bonusOption,
            },
          ],
        },
        callback: async ({ data, close }) => {
          const filmId = this.selectionList[0]?.film_id
          const episodeList = this.selectionList?.map(it => {
            return {
              id: it?.id,
              episode_no: it?.episode_no,
            }
          })
          const parms = {
            film_id: filmId,
            type: type === 'coins' ? 1 : 2,
            episode_list: JSON.stringify(episodeList),
            coins: data?.coins * 10000,
            valid_duration: data?.valid_duration,
          }
          type === 'coins' ? delete parms?.valid_duration : delete parms?.coins
          const resData = await editMoviesCoins(parms)
          if (resData.code === 0) {
            this.$message.success('修改成功')
          }
          this.getList()
          close()
        },
      })
    },
  },
  mounted() {
    this.handleSearch()
  },
}
</script>

<style lang="scss" scoped>
.movieName {
  font-weight: 600;
  font-size: 16px;
}
</style>
